<template>
  <el-table
    ref="tableRef"
    :data="props.data"
    :show-header="false"
    :row-key="(row) => row.ownerId"
    highlight-current-row
    @select="handleSelection"
    @row-click="handleRowClick"
  >
    <el-table-column type="selection" reserve-selection width="28" />
    <el-table-column>
      <template #default="scope">{{ scope.row.name }}</template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElTable } from "element-plus";
import { useComponentRef } from "@/hooks";

const props = defineProps<{
  data: Recordable[];
  checkList: Recordable[];
}>();

const emit = defineEmits(["checkChange"]);

const tableRef = useComponentRef(ElTable);
/** 是否被动触发 checkChange 事件 */
const passive = ref(false);

const handleSelection = (rows: Recordable[], row: Recordable) => {
  row.checked = !row.checked;
  emit("checkChange", row, rows);
};

const handleRowClick = (row: Recordable) => {
  passive.value = false;
  row.checked = !row.checked;

  tableRef.value!.toggleRowSelection(row, row.checked as boolean);
  emit("checkChange", row, getCheckedRows());
};

const setCheckedRows = (value: Recordable[]) => {
  passive.value = true;

  if (value.length) {
    const checkIds = value.map((m) => m.id);
    for (const row of props.data) {
      const checked = checkIds.includes(row.id);
      row.checked = checked;
      tableRef.value!.toggleRowSelection(row, checked);
    }
  } else {
    props.data.forEach((row) => {
      row.checked = false;
    });
    tableRef.value!.clearSelection();
  }
};

const getCheckedRows = () => tableRef.value!.getSelectionRows();

defineExpose({
  setCheckedRows,
  getCheckedRows
});
</script>
